package org.budo.validation.validator.impl;

import java.lang.annotation.Annotation;

import javax.validation.constraints.Pattern;

import org.budo.validation.exception.BudoPatternValidationException;
import org.budo.validation.validator.BudoValidator;

/**
 * @author lmw
 */
public class PatternValidator implements BudoValidator {
    public void validate(Annotation annotation, Integer parameterIndex, String parameterName, Object argumentValue) {
        Pattern pattern = (Pattern) annotation;
        String regexp = pattern.regexp();
        if (null != argumentValue && argumentValue instanceof CharSequence) {
            CharSequence charSequence = (CharSequence) argumentValue;
            boolean matches = java.util.regex.Pattern.matches(regexp, charSequence);
            if (!matches) {
                throw new BudoPatternValidationException(parameterIndex, parameterName, pattern, charSequence);
            }
        }
    }
}